<!-- 编辑弹窗 -->
<template>
  <ele-modal
    width="740px"
    :visible="visible"
    :close-on-click-modal="true"
    custom-class="ele-dialog-form"
    :title="isUpdate ? '修改用户信息' : '添加用户信息'"
    @update:visible="updateVisible"
  >
  <el-form ref="form" :model="form" :rules="rules" label-width="100px" >
      <el-card  style="margin-top: -10px">
      
        <el-row :gutter="20">
          <el-col :md="12" :sm="24">
            <el-form-item label="用户姓名:" prop="name">
              <el-input v-model="form.name" placeholder="请输入用户姓名"   >
                  <template slot="append"><el-select v-model="form.sex"  placeholder="性别" style="width: 80px; " class="ele-block" clearable>
                    <el-option v-for="(item, index) in sexList" :key="index" :label="item.Value" :value="item.Key" />
                </el-select></template>
              </el-input>
            </el-form-item>
          </el-col>
       
          <el-col :md="12" :sm="24">
            <el-form-item label="手机号码:" prop="phone"> 
              <el-input v-model="form.phone"  placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :md="12" :sm="24">
            <el-form-item label="所属组织:" prop="organizationalId">
                <ele-tree-select
                      :data="treeData"
                      v-model="form.organizationalId"
                      :clearable="true"
                      placeholder="请选择"
                      :default-expand-all="true"
                    />
            </el-form-item>
           
          </el-col>
          <el-col :md="12" :sm="24">
            <el-form-item label="证件号码:">
              <el-input v-model="form.idNumber" placeholder="请输入证件号码" />
            </el-form-item>
          </el-col>
        </el-row>
      
        <el-row :gutter="15">
          <el-col  :sm="12">
                <!-- <el-form-item label="电子邮箱:">
                  <el-input v-model="form.email" placeholder="请输入电子邮箱" />
                </el-form-item> -->
                
                <el-form-item label="入职日期:">
                  <el-date-picker v-model="form.inPositionDate" type="date" placeholder="选择入职日期"
                      format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd">
                  </el-date-picker>
              </el-form-item>
              <el-form-item label="离职日期:">
                <el-date-picker v-model="form.outPositionDate" type="date" placeholder="选择离职日期"
                    format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="联系地址:"  > 
              <el-input v-model="form.address"  placeholder="请输入联系地址" />
            </el-form-item>
          </el-col>
          <el-col  :sm="12" >
            <el-form-item label="用户照片:" >
              <el-upload action="#" ref="upload" list-type="picture-card"   :auto-upload="false" :file-list="fileList" :class="{ hide: hideUpload }" :on-change="handleChange" :limit="limit">
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{file}">
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" >
                  <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)" >
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span v-if="!removeDisable" class="el-upload-list__item-delete" @click="handleRemove(file,fileList)" >
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible" style="z-index:9999">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
     
        <el-row :gutter="20">
          <el-col  :sm="24">
           
            <el-form-item label="个人简介:">
              <el-input
                :rows="4"
                clearable
                type="textarea"
                :maxlength="200"
                v-model="form.remark"
                placeholder="请输入个人简介"
              />
            </el-form-item>
           </el-col>
         
          
        </el-row>   
  
      </el-card>
  </el-form>
  <div slot="footer">
    <el-button @click="updateVisible(false)">取消</el-button>
    <el-button type="primary" :loading="loading" @click="save" v-permission="'Basic_User_Save'" >
      保存
    </el-button>
  </div>
  </ele-modal>
</template>

<script>

  import upload from "@/components/UpLoad/index.js";
  import { QueryAttchmentByBusinessId ,GetGuid} from '@/api/attchment';
  import { AddUser, UpdateUser } from '@/api/usermanager/usermanager';
  import { QueryTreeView} from '@/api/usermanager/organizationmanager';
  //初始化对像
  import { QuerySexEnum } from '@/api/enummanger';

  export default {
    name: 'UserEdit',
    props: {
      // 弹窗是否打开
      visible: Boolean,
      // 修改回显的数据
      data: Object,
      
    },
    mixins: [upload],
    data() {
      return {
        // 表单数据
        form: {},
        // 表单验证规则
        rules: {
          name: [{required: true,message: '请输入姓名',trigger: 'blur'}],
          phone: [{required: true,message: '请输入手机号码',trigger: 'blur'}],
          organizationalId: [{required: true,message: '请选择组织',trigger: 'blur'}]
        },
        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false,
        //性别
        sexList:[],
        treeData:[]
      };
    },
    created(){
      this.querySexEnums();
     },
     mounted(){
      this.getTreeData();
      this.limit = 1;
     },
    methods: {
     async querySexEnums(){
      let sysEnums = await QuerySexEnum();
        sysEnums.map(e=>{
          this.sexList.push({Key:e.Key,Value:e.Value});
        });
      },
      async getTreeData(){
       await QueryTreeView().then((data)=>{
          this.treeData = data;
        });;
      },
  
      /* 保存编辑 */
      save() {
        //校验必填信息
        this.$refs['form'].validate((valid) => {
          if (!valid) {return false;}
          //日期时间
          this.loading = true;
          this.form.inPositionDate =  this.$util.toDateString(this.form.inPositionDate);
          this.form.outPositionDate =  this.$util.toDateString(this.form.outPositionDate);

          //上传图片
          this.fileList.map((f) => {
            if (f.file != undefined) {
              f.fileType = 1
              this.uploadImg(f);
            }
          });

          const saveOrUpdate = this.isUpdate ? UpdateUser : AddUser;
          saveOrUpdate(this.form)
            .then((msg) => {
              this.loading = false;
              this.$message.success(msg);
              this.updateVisible(false);

              //回调父组件方法
              this.$emit('done');
              this.fileList = [];
            })
            .catch((e) => {
              this.loading = false;
              this.$message.error(e.message);
            });
        });
      },

      /* 更新visible */
      updateVisible(value) {
        //更新父组件中的visible的值
        this.$emit('update:visible', value);
        //更新文件列表对像
        this.fileList= [];
      },

      //赋值到附件
      setAttchement(id){
         QueryAttchmentByBusinessId(id).then((d)=>{
          this.fileList = [];
          d.map((item)=>{
            this.fileList.push({
              id: item.id,
              name: item.fileName,
              url: item.fileAllPath,
              businessId: item.businessId,
              orderIndex: item.orderIndex,
            });
          });
          //设置上传图片按钮是否可见
          this.hideUpload = this.fileList.length >= this.limit;
        });
      },
      //上传图片
      handleChange(file, fileList) {
        let obj = {
          orderIndex: 1, //默认值
          attType: 1, //文件类型(1:图片,2:文件)
          file: file.raw, // 文件流
          fileName: file.name, // 文件名称
          url:file.url,// 文件路径
        }
        //索引
        if(fileList!=null && fileList.length>0){
          obj.orderIndex = fileList.length;
        }
        //业务id 新增页面时，从后台获取Guid
        if(this.form){
          obj.businessId = this.form.id;  
        }
        //文件列表
        this.fileList.push(obj);

        //设置上传图片按钮是否可见
        if(this.fileList!=null && this.fileList!=undefined){
          this.hideUpload = this.fileList.length >= this.limit;
        }else{
          this.hideUpload =false;
        }
      },

      /* 从后面获取主键 */
      async getId(){
        if(this.form.id){
        let id = await GetGuid();
        this.form.id = id;
        }
      },
    },

   
    /* 监听visible属性变化 */
    watch: {
      visible(visible) {
        if (visible) {
          if (this.data) {
            //赋值this.form
            this.form=this.data;
            // this.getTreeData();
            this.setAttchement(this.form.id);
            this.isUpdate = this.data.id !=null && this.data.id !=undefined;
          } else {
            this.form={}
            this.getId();
            this.fileList=[];
            this.isUpdate = false;
            this.hideUpload =false;
          }
        } else {
          //移除校验结果
          this.$refs['form'].clearValidate();
          this.form = {};
          this.getId();
        }
      }
    }
  };
</script>
